/*******************
This main.c file is for STC15F104E MCU controlling
1 buttons and 1 leds and 1 relay control 

Initial:
turn off led and relay

While button pushed,
light on the led and open relay, until 30 mins

*******************/
#include <reg51.h>
#include <intrins.h>

sbit	LED=P3^2;
sbit	RELAY=P3^3;
sbit	BUTTON=P3^4;

sfr		INT_CLKO=0x8f;
sfr		AUXR=0x8e;
sfr		P3M1=0xb1;
sfr		P3M0=0xb2;
sfr		CLK_DIV=0x97;

unsigned char sw=0;
unsigned char count1=0;
unsigned char count2=0;
unsigned int  t_count=0;
unsigned char time_out=0;
unsigned int  Threshold=0;

#define SysClk	46875L
#define T1MS	(65536-SysClk/1000)
#define T10MS	(65536-SysClk/100)
#define T100MS	(65536-SysClk/10)
#define T1S		(65536-SysClk)


void INT2_Routine(void);
void delay(void);

void main(void)
{
	//io intial
	CLK_DIV=0x07;//divide 6MHZ/128=46875hz
	P3M0=0x0c; //setting P3.2,P3.3 as output
	P3M1=0x10; //setting P3.4 as input,all others as bi-dir ports

	RELAY=0;//close the RELAY
	LED=1;//close the LED

	INT_CLKO=0x10;//enable int2 and close int 3 at the same time.
	TR0=0;//STOP running timer0
	ET0=0;//disable timer0 interrupt
	EA=1;

//	PCON=0x02;//power down the mcu, wait for int2 	
	t_count=0; //initial time counter
	time_out=0;

//  judge for different time-out time
	if(BUTTON==0)
		Threshold=60;
	else
		Threshold=1800;
	
	while(1)
	{
		if(time_out==1)
		{
		TR0=0;//STOP running timer0
		ET0=0;//disable timer0 interrupt
		time_out=0;
		t_count=0; //initial time counter
		RELAY=0;//close the RELAY
		LED=1;//close the LED	
		}
		_nop_();
		_nop_();
	}

}




void INT2_Routine(void) interrupt 10
{
	delay();
	if(BUTTON==0)
	{
		if(t_count==0)
		{
		RELAY=1;//open the RELAY
		LED=0;//open the LED

		//timer0 initial	
		AUXR=0x80; //timer0 work in 1T mode
		TMOD=0x00;//set timer0 as mode0 (16bit auto-reload)
		TL0=T1S;//low byte		
		TH0=T1S>>8;//high byte
		TR0=1;//start running timer0
		ET0=1;//enable timer0 interrupt

		t_count=0; //initial time counter		
		}

		if(t_count>0)
		{
		TR0=0;//STOP running timer0
		ET0=0;//disable timer0 interrupt
		time_out=0;
		t_count=0; //initial time counter
		
		RELAY=0;//close the RELAY
		LED=1;//close the LED
		}


	}

}


void delay(void)
{
unsigned int	j=0;
unsigned int 	k=0;
	for(k=0;k<6;k++)// k<4 old settings
	{
		for(j=0;j<200;j++)
		{
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		}
	
	}

}


void tm0_isr(void) interrupt 1 using 1
{
	t_count++;			//timer is set to interrupt every 1 second 
	if(t_count>=Threshold)	//t_count>=480(8 minutes),   t_count>=300(5 minutes),t_count>=1800(30 minutes),t_count>=60(1 minutes)
	{
	time_out=1;
	t_count=0;
	}
}






